<?php
class Cms_Plugin_Module extends Zend_Controller_Plugin_Abstract {
    
    public function preDispatch(Zend_Controller_Request_Abstract $request) 
    {
        $module = $request->getModuleName();
        $controller = $request->getControllerName();
        $layout = Zend_Layout::getMvcInstance();
        $layoutPath = $layout->getLayoutPath();
        if($controller != "error"){
            $layout->setLayoutPath($layoutPath.$module);
        }else{
            $layout->disableLayout();
        }
        
        // Load rules
        
        $mdRule = new Application_Model_DbTable_Rule();
        $rules = $mdRule->fetchDataPermission();
        
        // set Zend_Acl
        $acl = new Zend_Acl();
        $acl->allow();
        foreach($rules as $rule)
        {
           //add role
           $role = new Zend_Acl_Role($rule->group);
           if(!$acl->hasRole($role))
           {
                $acl->addRole($role);
           }
           
           // add ressources
           $resource = new Zend_Acl_Resource("$rule->module:$rule->controller");
           if(!$acl->has($resource))
           {
                $acl->add($resource);
           }           
           
           //set permission
           if(!$rule->allow)
           {
                $acl->deny($role, $resource, array($rule->action));
           }
        }
        // Lưu cache Zend_Acl
        
        //set global acl
        Zend_Registry::set("acl",$acl);
        
        $module = $request->getModuleName();
        $controller = $request->getControllerName();
        $action = $request->getActionName();        
        $resource = new Zend_Acl_Resource("$module:$controller");
        
        // Kiểm tra đăng nhập
        $auth = Zend_Auth::getInstance();
        $role = null;
        
        if($auth->hasIdentity()) 
        {
            $identity = $auth->getIdentity();
            
            $mdGroup = new Application_Model_DbTable_UserGroup();
            $row = $mdGroup->find($identity->groups_id)->current();
            
            $role = $row->groups_name;               
            if($acl->has($resource) && !$acl->isAllowed($role, $resource, $action))
            {
                
                $request->setModuleName("admin");
                $request->setControllerName("site");
                $request->setActionName("noauth");
                
            }   
        }        
        else
        {
           if($acl->has($resource) && !$acl->isAllowed($role,$resource, $action))
           {
                $request->setModuleName("admin");
                $request->setControllerName("user");
                $request->setActionName("login");
           }
        }
        
        
        $layout = Zend_Layout::getMvcInstance();
        $layout->getView()->navigation()->setAcl($acl)->setRole($role);
                  
    }
}
?>